//
//  QYTabBarVC.m
//  QingYue
//
//  Created by Zheng on 2019/3/19.
//  Copyright © 2019 com.lanou.product_A. All rights reserved.
//

#import "QYTabBarVC.h"
#import <CYLTabBarController.h>
#import "BaseViewController.h"
#import "BaseNavigationController.h"


static CGFloat const CYLTabBarControllerHeight = 40.f;

@interface QYTabBarVC () <CYLTabBarControllerDelegate>

@end

@implementation QYTabBarVC

- (instancetype)init {
    if (!(self = [super init])) {
        return nil;
    }
    
    UIEdgeInsets imageInsets = UIEdgeInsetsMake(-3.5, 0, 3.5, 0);
    UIOffset titlePositionAdjustment = UIOffsetMake(0, 0);
    CYLTabBarController *tabBarVC =
    [CYLTabBarController tabBarControllerWithViewControllers:self.viewControllers
                                       tabBarItemsAttributes:self.tabBarItemsAttributesForController
                                                 imageInsets:imageInsets
                                     titlePositionAdjustment:titlePositionAdjustment
                                                     context:nil];
    tabBarVC.delegate = (id)self;
    [self customizeTabBarAppearance:tabBarVC];
    return (self = (QYTabBarVC *)tabBarVC);
}

- (NSArray *)tabBarItemsAttributesForController {
    
    
    NSDictionary *homeAttri = @{
                                CYLTabBarItemTitle : @"推荐",
                                CYLTabBarItemImage : @"推荐灰",
                                CYLTabBarItemSelectedImage : @"推荐绿",
                                };
    
    NSDictionary *demandAttri = @{
                                  CYLTabBarItemTitle : @"馆藏",
                                  CYLTabBarItemImage : @"馆藏灰",
                                  CYLTabBarItemSelectedImage : @"馆藏绿",
                                  };
    
    NSDictionary *orderAttri = @{
                                 CYLTabBarItemTitle : @"书架",
                                 CYLTabBarItemImage : @"书架灰",
                                 CYLTabBarItemSelectedImage : @"书架绿",
                                 };
    
    NSDictionary *centerAttri = @{
                                  CYLTabBarItemTitle : @"更多",
                                  CYLTabBarItemImage : @"更多灰",
                                  CYLTabBarItemSelectedImage : @"更多绿",
                                  };
    
    NSArray *attri = @[homeAttri,demandAttri,orderAttri,centerAttri];
    return attri;
}

- (NSArray *)viewControllers {
    
    /*
     #import "QYHomeViewController.h"
     #import "QYHoldingViewController.h"
     #import "QYScanViewController.h"
     #import "QYBookShelfViewController.h"
     #import "QYMoreViewController.h"
     */
    
    NSArray *viewControllers = @[[self createControllerWithClassName:@"QYHomeViewController"],
                                 [self createControllerWithClassName:@"QYHoldingViewController"],
                                 [self createControllerWithClassName:@"QYBookShelfViewController"],
                                 [self createControllerWithClassName:@"QYMoreViewController"]];
    return viewControllers;
}

- (UINavigationController *)createControllerWithClassName:(NSString *)className {
    Class class = NSClassFromString(className);
    __kindof BaseViewController *vc = [[class alloc] init];
    BaseNavigationController *navVC = [[BaseNavigationController alloc] initWithRootViewController:vc];
    return navVC;
}

/**
 *  更多TabBar自定义设置：比如：tabBarItem 的选中和不选中文字和背景图片属性、tabbar 背景图片属性等等
 */
- (void)customizeTabBarAppearance:(CYLTabBarController *)tabBarController {
    // 自定义 TabBar 高度
    //    tabBarController.tabBarHeight = CYL_IS_IPHONE_X ? 65 : 40;
    
    // 普通状态下的文字属性
    NSMutableDictionary *normalAttrs = [NSMutableDictionary dictionary];
    normalAttrs[NSForegroundColorAttributeName] = RGB(74, 74, 74, 1.0);
    
    // 选中状态下的文字属性
    NSMutableDictionary *selectedAttrs = [NSMutableDictionary dictionary];
    selectedAttrs[NSForegroundColorAttributeName] = UIColorFromRGB(0x22cb64);
    
    // 设置文字属性
    UITabBarItem *tabBar = [UITabBarItem appearance];
    [tabBar setTitleTextAttributes:normalAttrs forState:UIControlStateNormal];
    [tabBar setTitleTextAttributes:selectedAttrs forState:UIControlStateSelected];
    
    // TabBarItem选中后的背景颜色
    [self customizeTabBarSelectionIndicatorImage];
    
    // 如果你的App需要支持横竖屏，请使用该方法移除注释 '//'
    [self updateTabBarCustomizationWhenTabBarItemWidthDidUpdate];
    
    [[UITabBar appearance] setBackgroundImage:[[UIImage alloc] init]];
    [[UITabBar appearance] setBackgroundColor:[UIColor clearColor]];
    [[UITabBar appearance] setTintColor:[UIColor whiteColor]];
    [[UITabBar appearance] setShadowImage:[[UIImage alloc] init]];
    
    [UITabBar appearance].translucent = NO;
    NSString *tabBarBackgroundImageName = @"tab_bg_white";
    UIImage *tabBarBackgroundImage = [UIImage imageNamed:tabBarBackgroundImageName];
    UIImage *scanedTabBarBackgroundImage = [[self class] scaleImage:tabBarBackgroundImage];
    [[UITabBar appearance] setBackgroundImage:scanedTabBarBackgroundImage];
    
    
}

- (void)updateTabBarCustomizationWhenTabBarItemWidthDidUpdate {
    void (^deviceOrientationDidChangeBlock)(NSNotification *) = ^(NSNotification *notification) {
        UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
        if ((orientation == UIDeviceOrientationLandscapeLeft) || (orientation == UIDeviceOrientationLandscapeRight)) {
            NSLog(@"Landscape Left or Right !");
        } else if (orientation == UIDeviceOrientationPortrait) {
            NSLog(@"Landscape portrait!");
        }
        [self customizeTabBarSelectionIndicatorImage];
    };
    [[NSNotificationCenter defaultCenter] addObserverForName:CYLTabBarItemWidthDidChangeNotification
                                                      object:nil
                                                       queue:[NSOperationQueue mainQueue]
                                                  usingBlock:deviceOrientationDidChangeBlock];
}

- (void)customizeTabBarSelectionIndicatorImage {
    CGFloat tabBarHeight = CYLTabBarControllerHeight;
    CGSize selectionIndicatorImageSize = CGSizeMake(CYLTabBarItemWidth, tabBarHeight);
    UITabBar *tabBar = [self cyl_tabBarController].tabBar ?: [UITabBar appearance];
    [tabBar setSelectionIndicatorImage:
     [[self class] imageWithColor:[UIColor whiteColor]
                             size:selectionIndicatorImageSize]];
}

+ (UIImage *)scaleImage:(UIImage *)image {
    CGFloat halfWidth = image.size.width/2;
    CGFloat halfHeight = image.size.height/2;
    UIImage *secondStrechImage = [image resizableImageWithCapInsets:UIEdgeInsetsMake(halfHeight, halfWidth, halfHeight, halfWidth) resizingMode:UIImageResizingModeStretch];
    return secondStrechImage;
}


+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size {
    if (!color || size.width <= 0 || size.height <= 0) return nil;
    CGRect rect = CGRectMake(0.0f, 0.0f, size.width + 1, size.height);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

#pragma mark - Life Cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 缩放动画
- (void)addScaleAnimationOnView:(UIView *)animationView repeatCount:(float)repeatCount {
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
    animation.keyPath = @"transform.scale";
    animation.values = @[@1.0,@0.75,@0.9,@1.0];
    animation.duration = 0.3;
    animation.repeatCount = repeatCount;
    animation.calculationMode = kCAAnimationCubic;
    [animationView.layer addAnimation:animation forKey:nil];
}

#pragma mark - UITabBarControllerDelegate
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
    [[self cyl_tabBarController] updateSelectionStatusIfNeededForTabBarController:tabBarController shouldSelectViewController:viewController];
    return YES;
}

- (void)tabBarController:(UITabBarController *)tabBarController didSelectControl:(UIControl *)control {
    
    if (tabBarController.selectedIndex != 2) {
        [self addScaleAnimationOnView:control repeatCount:1];
    }
    
    UIImpactFeedbackGenerator *feedBackGenertor = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleLight];
    [feedBackGenertor impactOccurred];
    
}

@end
